package com.bob.demo.api.controller;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import com.bob.demo.system.dao.UserRepository;
import com.bob.demo.system.model.User;
import com.bob.demo.utils.StringUtils;

import springfox.documentation.annotations.ApiIgnore;

@Controller
@RequestMapping(value = "/thymeleaf")
@ApiIgnore()
public class ThymeleafController {

	@Autowired
    private UserRepository userRepository;
	
    @RequestMapping(path = "/user", method = RequestMethod.GET)
    public ModelAndView index() {
//        List<User> userList = new ArrayList<User>;
        List<User> userList = userRepository.findAll();
//        User user = new User();
//		user.setId("1");
//		user.setUsername("jack");
//		user.setPassword("jack123");
//		user.setBirthday(new Date());
//        userList.add(user);
//        User user2 = new User();
//    	user2.setId("1");
//		user2.setUsername("lili");
//		user2.setPassword("1111111");
//		user2.setBirthday(new Date());
//        userList.add(user);
        ModelAndView modelAndView = new ModelAndView("user/user");
        modelAndView.addObject("userList", userList);
        return modelAndView;
    }
    
	@RequestMapping("/userList")
	public String userList(HttpServletRequest request, HttpServletResponse response, ModelMap modelMap) {
		
		String pageNoStr = request.getParameter("pageNo");
		String pageSizeStr= request.getParameter("pageSize");
		int pageNo = 0;
		int pageSize = 10;
		if(!StringUtils.isNullOrEmpty(pageNoStr)) {
			pageNo = Integer.parseInt(pageNoStr);
		}
		if(!StringUtils.isNullOrEmpty(pageSizeStr)) {
			pageSize = Integer.parseInt(pageSizeStr);
		}
		Sort sort = new Sort(Direction.DESC, "id");
		Pageable pageable = new PageRequest(pageNo, pageSize, sort);
		Page<User> userList = userRepository.findAll(pageable);
		modelMap.put("userList", userList.getContent());
		return "user/user";
	}
	
	@RequestMapping("demo")
	public String demo() {

		return "demo";
	}

}
